package com.gmss.crawler.task;

import com.alibaba.fastjson.JSONObject;
import com.gmss.crawler.module.paper.service.IPaperService;
import com.gmss.crawler.module.patent.service.IPatentService;
import com.gmss.crawler.module.publication.service.IPublicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 异步获取论文、专利、代表作品
 */
@Slf4j
@Service
public class PaperTask {

    @Resource
    private IPaperService iPaperService;
    @Resource
    private IPatentService iPatentService;
    @Resource
    private IPublicationService iPublicationService;

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1024,
            1024, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1024), new ThreadPoolFactory("PaperTask-data-task"));


    public void submit(JSONObject requestJSON, Long personId) {
        threadPoolExecutor.submit(new SyncDataThread(requestJSON, personId));
    }

    private class SyncDataThread implements Runnable {

        // 入参
        private JSONObject requestJSON;
        private Long personId;

        public SyncDataThread(JSONObject requestJSON, Long personId) {
            this.requestJSON = requestJSON;
            this.personId = personId;
        }

        @Override
        public void run() {
            //获取论文、专利、出版物 并入库
            try {
//                iPaperService.getPaperPatent(requestJSON, personId);
            } catch (Exception e) {
                log.info("PaperTask异常：request:[{}], Exception:[{}]", requestJSON, e);

            }
        }
    }

    @PreDestroy
    public void destroy() {
        if (null != this.threadPoolExecutor) {
            this.threadPoolExecutor.shutdown();
        }
    }
}
